#!/usr/bin/env bash
# 在 Linux ARM64 机器上直接安装和构建

set -euo pipefail

echo "=== 文本标注系统 Linux ARM64 构建脚本 ==="

# 检查 Python 版本
if ! command -v python3.12 >/dev/null 2>&1; then
    echo "错误: 未找到 Python 3.12"
    echo "请先安装 Python 3.12:"
    echo "  Ubuntu/Debian: sudo apt install python3.12 python3.12-venv python3.12-dev"
    echo "  CentOS/RHEL: sudo dnf install python3.12 python3.12-devel"
    exit 1
fi

# 创建虚拟环境
echo "创建虚拟环境..."
if [ ! -d .venv ]; then
    python3.12 -m venv .venv
fi

source .venv/bin/activate

# 升级基础工具
echo "升级 pip 和基础工具..."
pip install --upgrade pip setuptools wheel

# 安装依赖
echo "安装 Python 依赖..."
pip install -r requirements.txt

# 安装 PyInstaller
echo "安装 PyInstaller..."
pip install pyinstaller==6.11.1

# 构建二进制文件
echo "构建二进制文件..."
export PYTHONPATH="$(pwd):${PYTHONPATH:-}"

pyinstaller \
  --clean \
  --name textlabel-server \
  --onefile \
  --collect-all psycopg \
  --collect-binaries psycopg \
  --hidden-import app.main \
  --hidden-import app.db \
  --hidden-import app.redis_client \
  --hidden-import app.schemas \
  --hidden-import app.routers.labels \
  --hidden-import app.routers.texts \
  --hidden-import app.routers.annotations \
  --hidden-import app.routers.export_import \
  --add-data "app:app" \
  --collect-all app \
  --collect-submodules app \
  run_server.py

echo ""
echo "=== 构建完成 ==="
echo "二进制文件位置: $(pwd)/dist/textlabel-server"
echo "文件大小: $(du -h dist/textlabel-server | cut -f1)"
echo ""
echo "测试运行:"
echo "  ./dist/textlabel-server --help"
echo ""
echo "部署:"
echo "  sudo cp dist/textlabel-server /usr/local/bin/"
echo "  sudo chmod +x /usr/local/bin/textlabel-server"
